package com.itfitness.mchart.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.util.NetUtils;
import com.itfitness.mchart.R;
import com.itfitness.mchart.adapter.MChartFragmentPagerAdapter;
import com.itfitness.mchart.factory.DialogFactory;
import com.itfitness.mchart.fragment.ContactListFragment;
import com.itfitness.mchart.fragment.ConversationListFragment;
import com.itfitness.mchart.fragment.MineFragment;
import com.itfitness.mchart.listener.InviteNotifyListener;
import com.yinglan.alphatabs.AlphaTabsIndicator;
import com.yinglan.alphatabs.OnTabChangedListner;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    @BindView(R.id.activity_main_vp)
    ViewPager activityMainVp;
    @BindView(R.id.activity_main_ati)
    AlphaTabsIndicator activityMainAti;
    private ArrayList<Fragment> mFragments;
    private Boolean mOtherDeviceLogin = false;
    private AlertDialog otherDeviceLoginDialog;

    @Override
    protected int LayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean isHaveTitle() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initDatas();
        initListener();
    }

    /**
     * 注册账号监听（账号异地登录等）
     */
    private void addConnectionListener() {
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());
    }

    private void initListener() {
        setRightIcon(R.drawable.ic_add, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(AddFriendActivity.class);
            }
        });
        mImageView_RightIcon.setVisibility(View.GONE);//初始化的时候隐藏添加好友按钮
        activityMainAti.setOnTabChangedListner(new OnTabChangedListner() {
            @Override
            public void onTabSelected(int tabNum) {
                switch (tabNum){
                    case 0:
                        setTitle("会话", R.color.colorTitleText);
                        mImageView_RightIcon.setVisibility(View.GONE);
                        break;
                    case 1:
                        setTitle("联系人", R.color.colorTitleText);
                        mImageView_RightIcon.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        setTitle("我的", R.color.colorTitleText);
                        mImageView_RightIcon.setVisibility(View.GONE);
                        break;
                }
            }
        });
        activityMainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        setTitle("会话", R.color.colorTitleText);
                        mImageView_RightIcon.setVisibility(View.GONE);
                        break;
                    case 1:
                        setTitle("联系人", R.color.colorTitleText);
                        mImageView_RightIcon.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        setTitle("我的", R.color.colorTitleText);
                        mImageView_RightIcon.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initDatas() {
        setTitle("会话", R.color.colorTitleText);
        setBackIconShow(false);
        InviteNotifyListener.getInstance(this).listen();
        addConnectionListener();
        if(mFragments == null){
            mFragments = new ArrayList<>();
        }
        mFragments.add(new ConversationListFragment());
        mFragments.add(new ContactListFragment());
        mFragments.add(new MineFragment());
        MChartFragmentPagerAdapter mChartFragmentPagerAdapter = new MChartFragmentPagerAdapter(getSupportFragmentManager(),mFragments);
        activityMainVp.setAdapter(mChartFragmentPagerAdapter);
        activityMainVp.setOffscreenPageLimit(3);
        activityMainAti.setViewPager(activityMainVp);
    }

    @Override
    protected void onDestroy() {
        EMClient.getInstance().logout(false);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        ActivityUtils.startHomeActivity();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mOtherDeviceLogin){
            showOtherDeviceLoginDialog();
        }
    }

    /**
     * 显示其他设备登录弹窗
     */
    private void showOtherDeviceLoginDialog() {
        if(otherDeviceLoginDialog == null){
            otherDeviceLoginDialog = DialogFactory.createDefaultDialog(MainActivity.this, "检测到您的账号在其他设备登录", "重新登录", "退出登录", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //重新登录
                    EMClient.getInstance().logout(false);
                }
            }, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //退出登录
                    EMClient.getInstance().logout(false);
                    gotoActivity(LoginActivity.class);
                    finish();
                }
            });
            otherDeviceLoginDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    mOtherDeviceLogin = false;
                }
            });
        }
        otherDeviceLoginDialog.show();
    }

    /**
     * 监听账号状态
     */
    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }
        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除

                    }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        mOtherDeviceLogin = true;
                        try {
                            showOtherDeviceLoginDialog();
                        }catch (Exception e){

                        }
                    } else if(NetUtils.hasNetwork(MainActivity.this)) {
                        //连接不到聊天服务器
                        ToastUtils.showShort("连接不到聊天服务器");
                    }else{
                        //当前网络不可用，请检查网络设置
                        ToastUtils.showShort("当前网络不可用");
                    }
                }
            });
        }
    }
}
